package com.asp.intercepter;

import com.alibaba.fastjson.JSONObject;
import com.asp.constant.JwtClaimsConstant;
import com.asp.constant.MessageConstant;
import com.asp.context.BaseContext;
import com.asp.properties.JwtProperties;
import com.asp.result.Result;
import com.asp.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * author:          ndg
 * date:            2024/1/3
 */
@Component
@Slf4j
public class JwtTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 校验jwt
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        //1、从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getTokenName());

        //2、校验令牌
        try {
            log.info("jwt校验:{}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getSecretKey(), token);
            Object userName = claims.get(JwtClaimsConstant.USER_NAME);
            log.info("当前 用户名：{}", userName);
            BaseContext.setCurrentUserName((String) userName);
            //3、通过，放行
            return true;
        } catch (Exception ex) {
            log.info("令牌解析失败!");
            //创建响应结果对象
            Result responseResult = Result.error(MessageConstant.USER_NOT_LOGIN);
            //把Result对象转换为JSON格式字符串 (fastjson是阿里巴巴提供的用于实现对象和json的转换工具类)
            String json = JSONObject.toJSONString(responseResult);
            //设置响应头
            response.setContentType("application/json;charset=utf-8");
            //响应
            response.getWriter().write(json);
            return false;
        }
    }
}

